import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import { useDispatch } from 'react-redux'
import logo from '../../assets/logo.png'
import './index.scss'
import { loginAction } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router-dom'
const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  // console.log(location.state.from)
  const onFinish = async (values) => {
    // console.log('Success:', values)
    try {
      await dispatch(loginAction(values))
      message.success('登录成功')
      history.push(location.state?.from || '/home')
    } catch (error) {
      console.dir(error)
      message.error(error.response.data.message)
    }
  }
  // 函数校验
  /**
   *
   * @param {*} rule 当前表单项的校验规则
   * @param {*} value 当前表单项的值=>checkbox的值:true选中/false 未选中
   */
  const validateAgree = (rule, value) => {
    // console.log(rule, value)
    // value? Promise.resolve(): Promise.reject(new Error('Should accept agreement'))
    if (!value) {
      // 没有勾选
      return Promise.reject(new Error('请勾选用户协议'))
    }
    // 校验通过(必须)
    return Promise.resolve()
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          autoComplete="off">
          {/* 
            表单校验总结:
            1.Form.Item 组件上必须添加name 属性,name 属性和后台接口需要的参数名保持一直
            2.Form.Item 组件上加 rules 属性,添加校验规则
            3.通过 validateTrigger 指定校验规则触发时机:['onBlur', 'onChange']
            说明:在Form 组件上加 validateTrigger 作用于所有表单项
          */}
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: 'Please input your mobile!',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur',
              },
            ]}>
            <Input placeholder="请输入手机号" size="large" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
              { len: 6, message: '请输入6位验证码' },
            ]}>
            <Input.Password placeholder="请输入密码" size="large" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[{ validator: validateAgree }]}>
            {/* 非输入框，需要加valuePropName="checked" 属性 */}
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" size="large" block htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
